<?php
namespace Admin\Ims\Controllers;

use \Admin\Frontend\Controllers\ControllerBase;
use Admin\Models\ims\XHImsBoxIn;
use Admin\Models\ims\XHImsBoxOut;
use Admin\Models\ims\XHImsBrand;
use Admin\Models\ims\XHImsProdType;
use Admin\Models\ims\XHImsProduce;
use Admin\Models\ims\XHImsProduceIn;
use Admin\Models\ims\XHImsProduceOut;
use Admin\Models\ims\XHImsProduceType;
use Admin\Models\ims\XHImsProduct;
use Helpers\Assets;
use Helpers\Cache;
use Helpers\Hrm;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\XhException;
use Modules\Ims;
use Modules\Power;
use Modules\School;

class ProduceController extends ControllerBase{

    public static $enums = [
        'iProdAttr' => [1 => '普通商品', 2 => '自定义商品'] ,
    ];

    /**
     * 品牌列表
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180713
     */
    public function brandListAction(){
        $this->view->setTemplateBefore('listForm');
        Assets::easyUI('js/produce/brandList.js');
        $listSearchArr = $listButtonArr = [];
        if (Power::exist('Ims_Brand_Add')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if (Power::exist('Ims_Brand_Del')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ','style' => 'width:100px !important;');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        return $this->view->setVars([
            'List'          => Template::createList('list', 'brandList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ]);
    }

    /**
     * 获取品牌列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180713
     */
    public function getBrandAction(){
        try {
            $key = $this->request->getPost('key','string');
            $builder = $this->modelsManager->createBuilder()
                ->from('Admin\\Models\\ims\\XHImsBrand')
                ->columns('*')
                ->where('bDelete= 0 ');
            if ($key) {
                $builder->andWhere(' sBrand like :key:', ['key' => '%'.$key.'%']);
            }
            $data = Main::runBuilderPage($builder);
            Main::runUserNameById($data['rows'], ['iCreateUserId' => 'iCreateUserId' , 'iLastModifyUserId' => 'iLastModifyUserId'], true);
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     *  新增品牌
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180713
     */
    public function saveBrandAction(){
        try {
            $id = $this->request->getPost('id','int');
            if ($id) {
                $obj = XHImsBrand::findFirst($id);
                if (!User::isAdmin() || ! (Main::getLoginUserInfo('userId') == $obj->iCreateUserId && Power::exist('Ims_Brand_Edit'))) {
                    return $this->sendErrorResponse(400, '缺少权限');
                }
            } else {
                $obj = new XHImsBrand();
            }
            $obj->assign($this->request->getPost());
            if ($this->checkBrand($obj->iPBId, $obj->sBrand)) {
               return $this->sendErrorResponse(500, '品牌名称重复');
            }
            if (!$obj->save()){
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 验证品牌名称是否重复
     *
     * @param $id
     * @param $name
     *
     * @return bool
     *
     * create by dale  20180716
     */
    private function checkBrand($id,$name){
        if ($id) {
            $obj = XHImsBrand::findFirst([
                'conditions' => 'bDelete = 0 and iPBId != :iPBId: and sBrand = :sBrand:',
                'bind'       => ['iPBId' => $id , 'sBrand' => $name]
            ]);
        } else {
            $obj = XHImsBrand::findFirst([
                'conditions' => 'bDelete = 0  and sBrand = :sBrand:',
                'bind'       => ['sBrand' => $name]
            ]);
        }
        return $obj ? true : false;
    }

    /**
     * 删除品牌
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180713
     */
    public function delBrandAction(){
        try {
            $this->db->begin();
            $ids = $this->request->getPost('ids', 'int');
            if (is_string($ids)) {
                $ids = explode(',', $ids);
            }
            $objArr = XHImsBrand::find([
                'conditions' => 'bDelete = 0 and iPBId in ({ids:array})',
                'bind'       => ['ids' => $ids]
            ]);
            foreach ($objArr as $obj) {
                if(User::isAdmin() || $obj->iCreateUserId == Main::getLoginUserInfo('userId')) {
                    if (!$obj->delete()) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(500, '保存失败');
                    }
                } else {
                   continue;
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('删除成功，已过滤无法删除数据');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 获取类型
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180711
     */
    public function getTypeAction(){
        $key = $this->request->getPost('key','string');
        try {
            $builder = $this->modelsManager->createBuilder()
                ->from('Admin\\Models\\ims\\XHImsProduceType')
                ->columns('*')
                ->where('bDelete= 0');
            if ($key) {
                $builder->andWhere('sType like :key:', ['key' => '%'.$key.'%']);
            }
            $data = $builder->getQuery()->execute()->toArray();
            Main::runUserNameById($data, ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId'], true);
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 删除成功
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180711
     */
    public function delTypeAction(){
        try {
            $this->db->begin();
            $id = $this->request->getPost('id', 'int');
            if (!$id) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XHImsProduceType::findFirst($id);
            if (!User::isAdmin() && $obj->iCreateUserId != Main::getLoginUserInfo('userId')) {
                return $this->sendErrorResponse(403, '没有权限');
            }
            if (!$obj->delete()) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '删除失败');
            }
            $prods = XHImsProduce::find([
                'conditions' => 'bDelete = 0 and iPTId = :iPTId:',
                'bind'       => [ 'iPTId' => $id]
            ]);
            if ($prods->toArray()) {
                foreach ($prods as $prod) {
                    if (!$prod->delete()) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(500, '商品删除失败');
                    }
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('删除成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }


    /**
     * 保存类型
     *
     * create by xjq 20180711
     */
    public function saveTypeAction(){
        try {
            $id   = $this->request->getPost('id', 'int');
            $name = $this->request->getPost('name','string');
            if ($id) {
                $obj = XHImsProduceType::findFirst($id);
            } else {
                $obj = new XHImsProduceType();
            }
            if ($id) { //修改
                if (!User::isAdmin() && $obj->iCreateUserId != Main::getLoginUserInfo('userId')) {
                    return $this->sendErrorResponse(403, '没有权限');
                }
            }
            $obj->sType = $name;
            if ($this->checkType($obj->iPTId, $obj->sType)) {
                return $this->sendErrorResponse(500, '该类型已经存在');
            }
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 检查类型
     *
     * @param $id
     * @param $name
     *
     * @return bool
     *
     * create by dale  20180716
     */
    private function checkType($id, $name){
        if ($id) {
            $obj = XHImsProduceType::findFirst([
                'conditions' => 'bDelete = 0 and iPTId != :iPTId: and sType = :sType:',
                'bind'       => ['iPTId' => $id , 'sType' => $name]
            ]);
        } else {
            $obj = XHImsProduceType::findFirst([
                'conditions' => 'bDelete = 0  and sType = :sType:',
                'bind'       => ['sType' => $name]
            ]);
        }
        return $obj ? true : false;
    }


    /**
     * 商品列表
     *
     * @return \Phalcon\Mvc\View
     *
     * create by xjq 20180711
     */
    public function produceListAction(){
        $this->view->pick('produce/produceList');
        Assets::easyUI();
        Assets::importMainJs('assets/easyui/datagrid-detailview.js');
        Assets::importJs('js/produce/produceList.js');
        $typeListButton = $prodListButton = $typeSearchArr = $prodSearchArr = [];
        if(Power::exist('Ims_ProdList_Add')){
            $typeListButton[] = array('plain' => 'true', 'id' => 'bt_type_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if(Power::exist('Ims_ProdList_Del')){
            $typeListButton[] = array('plain' => 'true', 'id' => 'bt_type_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        if(Power::exist('Ims_ProdList_Add')){
            $prodListButton[] = array('plain' => 'true', 'id' => 'bt_prod_add', 'text' => '新增', 'icon' => 'fa-plus');
            $prodListButton[] = array('plain' => 'true', 'id' => 'bt_prod_customProd', 'text' => '自定义商品', 'icon' => 'fa-tasks');
        }
        if (Power::exist('Ims_ProdList_Accessory')) {
            $prodListButton[] = array('plain' => 'true', 'id' => 'bt_prod_accessory', 'text' => '配件', 'icon' => 'fa-paperclip');
        }
        if(Power::exist('Ims_ProdList_Del')){
            $prodListButton[] = array('plain' => 'true', 'id' => 'bt_prod_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        $typeSearchArr[] = array('type' => 'text', 'id' => 'type_search','style' => 'width:100px !important;');
        $typeSearchArr[] = array('type' => 'button', 'id' => 'bt_type_search', 'text' => '查找', 'icon' => 'fa-search','style' => 'margin-left:10px');
        $prodSearchArr[] = array('type' => 'select', 'id' => 'prod_part', 'data' => ['' =>'—全部—', 1 => '非部件', 2 => '部件'], 'default' => '');
        $prodSearchArr[] = array('type' => 'select', 'id' => 'prod_brand', 'data' => XHImsBrand::getBrandEnum() + ['' => '——品牌——'], 'default' => '');
        $prodSearchArr[] = array('type' => 'select', 'id' => 'prod_attr', 'data' => self::$enums['iProdAttr'] + ['' => '商品属性'], 'default' => '');
        $prodSearchArr[] = array('type' => 'text', 'id' => 'prod_search', 'label' => ' 搜索： ','style' => 'width:100px !important;');
        $prodSearchArr[] = array('type' => 'button', 'id' => 'bt_prod_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        return $this->view->setVars([
            'typeList' => Template::createList('typeList', 'produceTypeList', [
                'searchToolbar' => Template::createSearchToolBar($typeSearchArr, !!$typeListButton),
                'buttonToolbar' => Template::createButtonToolBar($typeListButton),
            ]),
            'prodList' => Template::createList('prodList', 'produceList', [
                'searchToolbar' => Template::createSearchToolBar($prodSearchArr, !!$prodListButton),
                'buttonToolbar' => Template::createButtonToolBar($prodListButton),
            ]),
        ]);
    }


    /**
     * 获取商品列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180711
     */
    public function getProduceAction(){
        try {
            $typeId = $this->request->getPost('iPTId', 'int', '0');//分类id
            $attr = $this->request->getPost('attr', 'int');
            $part = $this->request->getPost('part', 'int');
            $brand = $this->request->getPost('brand', 'int');
            $key   = $this->request->getPost('key', 'string');
            $builder = $this->modelsManager->createBuilder()
                ->from('Admin\\Models\\ims\\XHImsProduce')
                ->where('bDelete = 0');
            if ($typeId) {
                $builder->andWhere('iPTId = :iPTId:', ['iPTId' => $typeId]);
            }
            if ($attr) {
                $builder->andWhere('iProdAttr = :attr:', ['attr' =>$attr]);
            }
            if ($part) {
                $builder->andWhere('bParts = :part:', ['part' => $part-1]);
            }
            if ($brand) {
                $builder->andWhere('iPBId = :iPBId:', ['iPBId' => $brand]);
            }
            if ($key) {
                $builder->andWhere('sProdName like :key:', '%'.$key.'%');
            }
            if(!User::isAdmin()){
                $nowUserId = Main::getLoginUserInfo('userId');
                $depArr = User::getExtraPower('dep', 'prod', $nowUserId);
                if($depArr){ //有额外权限
                    $userIds = Hrm::getUserByDepId($depArr, true);
                    if ($userIds) {
                        $builder->andWhere('iCreateUserId in ({ids:array}) or iCreateUserId = :userId:',
                            ['ids' => $userIds, 'userId' => $nowUserId]);
                    } else {
                        $builder->andWhere(' iCreateUserId = :userId:', ['userId' => $nowUserId]);
                    }
                }else{
                    $builder->andWhere(' iCreateUserId = :userId:', ['userId' => $nowUserId]);
                }
            }
            $data = Main::runBuilderPage($builder,[
                'iPTId'     => XHImsProduceType::getProduceTypeEnum(),
                'iProdAttr' => self::$enums['iProdAttr'],
                'bParts'    => [1 => '是' , 0 => '否'],
                'iPBId'     => XHImsBrand::getBrandEnum()
            ]);
            $prods = XHImsProduce::getParts();
            foreach ($data['rows'] as &$row) {
                $row['extra'] = '';
                if ($row['iProdAttr'] == '自定义商品') {
                    $row['mParts'] = unserialize($row['mParts']);
                    if ($row['mParts']) {
                        $row['extra'] = '<table><tr><th style="text-align: center">部件</th><th style="text-align: center">数量</th></tr>';
                        foreach ($row['mParts'] as $item) {
                            $row['extra'] .= '<tr><td style="width: 200px;">' . $prods[$item['prodId']] . '</td><td style="width: 100px;text-align: right">' . $item['num'] . '</td></tr>';
                        }
                        $row['extra'] .='</table>';
                    }
                }
            }
            Main::runUserNameById($data['rows'], ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId'], true);
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 获取商品列表
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180712
     */
    public function prodFormAction(){
        $iPTId = $this->request->getQuery('currentType','int');
        if ($iPTId) {
            $this->view->setVar('iPTId', $iPTId);
        }
        $this->view->pick('produce/prodForm');
        Assets::importJs('js/produce/prodForm.js');
        $id = $this->request->getQuery('id','int');
        if ($id) {
            $obj = XHImsProduce::findFirst($id);
            if (!$obj) {
                return $this->sendViewError('未找到该商品对象');
            }
            if (!User::isAdmin() && !(Main::getLoginUserInfo('userId') == $obj->iCreateUserId && Power::exist('Ims_ProdList_Edit'))) {
                $this->view->setVar('powerScript', '<script>parent.$(\'#bt_modal_confirm\').hide();</script>');
            }
            $this->view->setVar('formData', $obj->toArray());
        }
        return $this->view->setVars([
            'prodTypes' => XHImsProduceType::getProduceTypeEnum(),
            'brand'     => XHImsBrand::getBrandEnum()
        ]);
    }

    /**
     * 删除商品
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180711
     */
    public function delProduceAction(){
        try {
            $id = $this->request->getPost('id', 'string');
            $obj = XHImsProduce::findFirst($id);
            if (!User::isAdmin() && $obj->iCreateUserId != Main::getLoginUserInfo('userId')) {
                return $this->sendErrorResponse(400, '没有权限');
            }
            if (!$obj->delete()) {
                return $this->sendErrorResponse(500, '删除失败');
            }
            return $this->sendSuccessResponse('删除成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 保存商品
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180711
     */
    public function saveProduceAction()
    {
        try {
            $iProdId  = $this->request->getPost('iProdId', 'int');
            $postData = $this->request->getPost();
            $prodArr  = $this->request->getPost('prods');
            if ($iProdId) {
                $obj = XHImsProduce::findFirst($iProdId);
                if (!User::isAdmin() && !(Main::getLoginUserInfo('userId') == $obj->iCreateUserId && Power::exist('Ims_ProdList_Edit'))) {
                    return $this->sendErrorResponse(400, '没有权限');
                }
            } else {
                $obj = new XHImsProduce();
            }
            $obj->assign($postData);
            if ($prodArr) {
                if (count(array_filter($prodArr)) != count(array_filter(array_unique(array_column($prodArr, 'prodId'))))) { //判断重复
                    return $this->sendErrorResponse(500, '部件有重复');
                }
                $obj->mParts = $prodArr;
            }
            if ($this->checkProd($obj->iProdId, $obj->sProdName)) {
                return $this->sendErrorResponse(500, '该商品已经存在');
            }
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 验证商品是否存在
     *
     * @param $id
     * @param $name
     *
     * @return bool
     *
     * create by dale  20180716
     */
    private function checkProd($id, $name){
        if ($id) {
            $obj = XHImsProduce::findFirst([
                'conditions' => 'bDelete = 0 and iProdId != :iProdId: and sProdName = :sProdName:',
                'bind'       => ['iProdId' => $id , 'sProdName' => $name]
            ]);
        } else {
            $obj = XHImsProduce::findFirst([
                'conditions' => 'bDelete = 0  and sProdName = :sProdName:',
                'bind'       => ['sProdName' => $name]
            ]);
        }
        return $obj ? true : false;
    }
    /**
     * 自定义商品
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20180712
     */
    public function customProdAction(){
        $iPTId = $this->request->getQuery('currentType','int');
        if ($iPTId) {
            $this->view->setVar('iPTId', $iPTId);
        }
        $this->view->pick('produce/customProd');
        Assets::select2();
        Assets::importJs('js/produce/customProd.js');
        $id = $this->request->getQuery('id','int');
        if ($id) {
            $obj = XHImsProduce::findFirst($id);
            if (!$obj) {
                return $this->sendViewError('未找到该商品对象');
            }
            if (!User::isAdmin() && !(Main::getLoginUserInfo('userId') == $obj->iCreateUserId && Power::exist('Ims_ProdList_Edit'))) {
                $this->view->setVar('powerScript', '<script>parent.$(\'#bt_modal_confirm\').hide();</script>');
            }
            $this->view->setVar('formData', $obj->toArray());
        }
        return $this->view->setVars([
            'prodTypes' => XHImsProduceType::getProduceTypeEnum(),
            'parts'     => XHImsProduce::getParts()
        ]);
    }

    /**
     * 获取商品数量
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180718
     */
    public function getProdNumAction(){
        try {
            $id  = $this->request->getPost('id','string');
            $num = Ims::getProdCurrentNum($id);
            return $this->sendJsonResponse(['num' => $num]);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 获取商品信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180719
     */
    public function getProdInfoAction(){
        $id = $this->request->getPost('id', 'string');
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $obj = XHImsProduce::findFirst($id);
        if (!$obj) {
            return $this->sendErrorResponse(400, '未找到当前id对应的对象');
        }
        return $this->sendJsonResponse($obj->toArray());
    }

    /**
     * 平板转移
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180723
     */
    public function transTypeAction(){
        try {
            $this->db->begin();
            $typeNameArr = ['充电设备', '平板', '平板壳'];
            $types = XHImsProdType::find([
                'conditions' => 'bDelete = 0 and sTypeName in ({names:array})',
                'bind'       => ['names' => $typeNameArr]
            ]);
            foreach ($types as $type) {
                $sql = "insert into  XHIms_ProduceType(iPTId,sType,iCreateUserId,tCreateDate,iLastModifyUserId,tLastModifyDate) values  ";
                $conditions = [];
                $conditions [] = " {$type->iTypeId} ";
                $conditions [] = " '{$type->sTypeName}' ";
                $conditions [] = " '{$type->iCreateUserId}' ";
                $conditions [] = " '{$type->tCreateDate}' ";
                $conditions [] = " '{$type->iLastModifyUserId}' ";
                $conditions [] = " '{$type->tLastModifyDate}' ";
                $sql .= '('. implode(' , ', $conditions) . ')';
                if (!$this->db->execute($sql)){
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '类型保存失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('类型转移成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 商品转移
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180723
     */
    public function transProdAction(){
        try {
            $this->db->begin();
            $types = XHImsProduceType::find([
                'conditions' => 'bDelete = 0'
            ])->toArray();
            $types = array_column($types, 'iPTId');
            $prods = XHImsProduct::find([
                'conditions' => 'iTypeId in ({ids:array})',
                'bind'       => ['ids' => $types]
            ]);
            foreach ($prods as $index => $prod) {
                $sql = "insert into XHIms_Produce";
                $conditions = [];
                $conditions['iProdId']   = $prod->iProdId;
                $conditions['iPTId']     = $prod->iTypeId;
                $conditions['sMeasure']  = $prod->sMeasures;
                $conditions['sProdName'] = $prod->sProdName;
                $conditions['dOutPrice'] = $prod->iOutPrice;
                $conditions['dInPrice']  = $prod->iInPrice;
                $conditions['bDelete']   = $prod->bDelete;
                $conditions ['iCreateUserId'] = $prod->iCreateUserId;
                $conditions ['tCreateDate'] = $prod->tCreateDate;
                $conditions ['iLastModifyUserId'] = $prod->iLastModifyUserId;
                $conditions ['tLastModifyDate'] = $prod->tLastModifyDate;
                $sql .= '(' . implode(',', array_keys($conditions)) . ') ';
                $sql .= "values ( '". implode(" ',' ", array_values($conditions)) ."' )";
                if (!$this->db->execute($sql)) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '商品列表保存失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('商品列表转移成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 入库转移
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180723
     */
    public function transInAction(){
        try {
            $this->db->begin();
            $prods = XHImsProduce::find([
                'conditions' => 'bDelete = 0'
            ])->toArray();
            $prods = array_column($prods, 'iProdId');
            $boxs = XHImsBoxIn::find([
                'conditions' => 'iProdId in ({ids:array})',
                'bind'       => ['ids' => $prods]
            ]);
            foreach ($boxs as $box) {
                $sql = "insert into XHIms_ProduceIn";
                $conditions = [];
                $conditions['iPInId']   = $box->iBoxId;
                $conditions['iProdId']  = $box->iProdId;
                if ($box->sRemark && strpos($box->sRemark, '维修') !== false) {
                    $conditions['iInType']  = 3;
                } else {
                    $conditions['iInType']  = 1;
                }
                $conditions['iInNum']   = $box->iProdNum;
                $conditions['dInPrice'] = $box->iInPrice;
                $conditions['mDesc'] = $box->sRemark;
                $conditions['bDelete']   = $box->bDelete;
                $conditions ['iCreateUserId'] = $box->iCreateUserId;
                $conditions ['tCreateDate'] = $box->tCreateDate;
                $conditions ['iLastModifyUserId'] = $box->iLastModifyUserId;
                $conditions ['tLastModifyDate'] = $box->tLastModifyDate;
                $sql .= '(' . implode(',', array_keys($conditions)) . ') ';
                $sql .= "values ( '". implode(" ',' ", array_values($conditions)) ."' )";
                if (!$this->db->execute($sql)) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '入库明细保存失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('入库明细转移成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 出库转移
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180724
     */
    public function transOutAction(){
        try {
            $this->db->begin();
            $prods = XHImsProduce::find([
                'conditions' => 'bDelete = 0'
            ])->toArray();
            $prods = array_column($prods, 'iProdId');
            $boxs = XHImsBoxOut::find([
                'conditions' => 'iProdId in ({ids:array})',
                'bind'       => ['ids' => $prods]
            ]);
            foreach ($boxs as $box) {
                $sql = "insert into XHIms_ProduceOut";
                $conditions = [];
                $conditions['iPOutId']   = $box->iBOutId;
                $conditions['iProdId']  = $box->iProdId;
                if ($box->sRemark && strpos($box->sRemark, '申领') !== false) {
                    $conditions['iOutType']  = 2;
                } else {
                    $conditions['iOutType']  = 1;
                }
                $conditions['iOutNum']   = $box->iOutNum;
                $conditions['iChargeMode'] = $box->iChargeMode;
                $conditions['dOutPrice'] = $box->iOutPrice;
                $conditions['mDesc'] = $box->sRemark;
                $conditions['iSchoolId'] = $box->iSchoolId;
                $conditions['bDelete']   = $box->bDelete;
                $conditions ['iCreateUserId'] = $box->iCreateUserId;
                $conditions ['tCreateDate'] = $box->tCreateDate;
                $conditions ['iLastModifyUserId'] = $box->iLastModifyUserId;
                $conditions ['tLastModifyDate'] = $box->tLastModifyDate;
                if (isset($box->iBPCId) && $box->iBPCId) {
                    $conditions['iOutTypeId'] = $box->iBPCId;
                    $conditions['iOutType'] = 3;
                }
                $sql .= '(' . implode(',', array_keys($conditions)) . ') ';
                $sql .= "values ( '". implode(" ',' ", array_values($conditions)) ."' )";
                if (!$this->db->execute($sql)) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '出库明细保存失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('出库明细转移成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 更新库存
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180724
     */
    public function updateProdNumAction(){
        try {
            $this->db->begin();
            $id = $this->request->get('id','int');
            if ($id) {
                $obj = XHImsProduce::findFirst($id);
                if(!$obj){
                    return $this->sendErrorResponse(400, '未找到商品');
                }
                $in = XHImsProduceIn::find([
                    'conditions' => 'bDelete = 0 and iProdId = :iProdId:',
                    'bind'    => ['iProdId' => $id]
                ])->toArray();
                $out = XHImsProduceOut::find([
                    'conditions' => 'bDelete = 0 and iProdId = :iProdId:',
                    'bind'    => ['iProdId' => $id]
                ])->toArray();
                $total = 0;
                if ($in) {
                    foreach ($in as $row) {
                        $total += $row['iInNum'];
                    }
                }
                if ($out) {
                    foreach ($out as $row) {
                        $total -= $row['iOutNum'];
                    }
                }
                $obj->iCurrentNum = $total;
                if (!$obj->save()) {
                    $this->db->rollback();
                   return $this->sendErrorResponse(500,'保存');
                }
            } else {
                $in = XHImsProduceIn::find([
                    'conditions' => 'bDelete = 0 '
                ])->toArray();
                $out = XHImsProduceOut::find([
                    'conditions' => 'bDelete = 0 '
                ])->toArray();
                $arr = [];
                foreach ($in as $row) {
                    $arr[$row['iProdId']] = Tool::getValue($arr, $row['iProdId'], 0) + $row['iInNum'];
                }
                foreach ($out as $row) {
                    $arr[$row['iProdId']] = Tool::getValue($arr, $row['iProdId'], 0) - $row['iOutNum'];
                }
                $prodArr = XHImsProduce::find([
                    'conditions' => 'bDelete = 0'
                ]);
                foreach ($prodArr as $prod) {
                    $prod->iCurrentNum = Tool::getValue($arr, $prod->iProdId, 0);
                    if (!$prod->save()) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(500, '保存成功');
                    }
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('更新成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 转移数据库
     *
     * create by dale  20180730
     */
    public function moveDbAction(){
        $response = $this->transTypeAction();
        if (json_decode($response->getContent(), true)['code'] != 200) {
            return $this->sendErrorResponse(400 ,'类型保存失败');
        }
        $response = $this->transProdAction();
        if (json_decode($response->getContent(), true)['code'] != 200) {
            return $this->sendErrorResponse(400 ,'商品保存失败');
        }
        $response = $this->transInAction();
        if (json_decode($response->getContent(), true)['code'] != 200) {
            return $this->sendErrorResponse(400 ,'入库保存失败');
        }
        $response = $this->transOutAction();
        if (json_decode($response->getContent(), true)['code'] != 200) {
            return $this->sendErrorResponse(400 ,'出库保存失败');
        }
        $response = $this->updateProdNumAction();
        if (json_decode($response->getContent(), true)['code'] != 200) {
            return $this->sendErrorResponse(400 ,'数目保存失败');
        }
        return $this->sendSuccessResponse('转移成功');
    }


    /**
     * 附件表单
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20190124
     */
    public function accessoryFormAction()
    {
        try {
            $id = $this->request->getQuery('id', 'string');
            if (!$id) {
                return $this->sendViewError('缺少参数');
            }
            $prod = XHImsProduce::findFirst($id);
            $this->view->pick('produce/accessoryForm');
            Assets::select2();
            Assets::importJs('js/produce/accessoryForm.js');
            return $this->view->setVars([
                'formData' => $prod->toArray(),
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }

    /**
     * 保存配件
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20190124
     */
    public function saveAccessoryAction()
    {
        if (!Power::exist('Ims_ProdList_Accessory')) {
            return $this->sendErrorResponse(403, '没有权限');
        }
        $prodId = $this->request->getPost('iProdId', 'string');
        if (!$prodId) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $content = $this->request->getPost('mContent');
        $obj = XHImsProduce::findFirst($prodId);
        if (!$obj) {
            return $this->sendErrorResponse(400, '未找到改商品信息');
        }
        try {
            if ($content) {
                $nameList = array_values(array_filter(array_unique(array_column($content, 'name'))));
                if (count($nameList) != count($content)) {
                    throw new \Exception('存在重复的配件名称');
                }
                foreach ($content as $index => $row) {
                    if ($row['num'] <= 0) {
                        unset($content[$index]);
                    }
                }
                $obj->mAccessory = array_values($content);
            } else {
                $obj->mAccessory = $content;
            }
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }


}